package com.zhouyiquan.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhouyiquan.dao.ProvinceDao;
import com.zhouyiquan.dao.impl.ProvinceDaoImpl;
import com.zhouyiquan.entity.Province;
import com.zhouyiquan.service.ProvinceService;
import com.zhouyiquan.util.JedisPoolUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.List;

/**
 * @author: 周益全（https://www.zhouyiquan.site）
 * @Date: Created in 2022/09
 * @Descript:
 */
public class ProvinceServiceImpl implements ProvinceService {
    private ProvinceDao dao = new ProvinceDaoImpl();
    @Override
    public List<Province> findAll() {
        return dao.findAll();
    }

    /**
     * 使用 rdies 缓存
     * @return
     */
    @Override
    public String findAllJson() {
        //获取jedis客户端连接
        Jedis jedis = JedisPoolUtils.getJedis();
        String province_json = jedis.get("province");
        
        if(province_json == null || province_json.length() == 0){
            //从数据库中查询
            System.out.println("redis没有数据，查询数据库");
            List<Province> ps = dao.findAll();


            //将数据序列化
            ObjectMapper mapper = new ObjectMapper();
            try {
                province_json = mapper.writeValueAsString(ps);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }


            //将 json 数据存入 redis
            jedis.set("province",province_json);
            jedis.close();
        }else {
            System.out.println("redis中有数据....");
        }
        return province_json;
    }
}
